<template>
  <div>
    <el-header style="display: flex; align-items: center; justify-content: flex-start; padding-left: 5px; margin-top:5px; margin-bottom:5px">
    <i class="el-icon-location-information" style="font-size:20px; margin-right:5px">
    当前位置：主计划信息
    </i>
    </el-header>
    <div>
    <el-tabs 
      v-model="activeTab" 
      @tab-click="handleTabClick" 
      class="full-width-tabs"
      tab-position="top">
      <el-tab-pane label="整机级" name="content1"></el-tab-pane>
      <el-tab-pane label="站位级" name="content2"></el-tab-pane>
    </el-tabs>



  </div>
    
    <div v-if="activeContent === 'content1'">
              
    <div class="search" style="display: flex; align-items: center; justify-content: space-between; padding-left: 5px;">
       <div style="display: flex; align-items: center;">
        

        <input type="text" v-model="searchKeyword" placeholder="输入关键词搜索" style="margin-right: 10px; width: 200px;">
        <button @click="search">
          <i class="el-icon-search"></i>
        </button>
       </div>
       <div style="display: flex; align-items: center;">
        <button @click="fetchData" style="margin-left: 50px;">加载数据库内容</button>
        <button @click="exportToExcel" style="margin-left: 50px;">导出为Excel</button>
       </div>
      </div>
    <div class="table-container">
    <table class="custom-table">
      <thead>
        <tr>
          <th>序号</th>
          <th>直升机编号</th>
          <th>产线</th>
          <th>机型</th>
          <th>批次</th>
          <th>开始装配时间</th>
          <th>指令交付节点</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(item, index) in currentData" :key="item.field1">
          <td>{{ index+1+(currentPage-1)*itemsPerPage }}</td>
          <td>{{ item.field1 }}</td>
          <td>{{ item.field2 }}</td>
          <td>{{ item.field3 }}</td>
          <td>{{ item.field4 }}</td>
          <td>{{ item.field5 }}</td>
          <td>{{ item.field6 }}</td>
        </tr>
      </tbody>
    </table>
    </div>

    <div class="pagination">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="userItemsPerPage"
        layout="total, sizes, prev, pager, next, jumper"
        :total="data.length">
      </el-pagination>
    </div>
    </div>


      <div v-else-if="activeContent === 'content2'">
               
    <div class="search" style="display: flex; align-items: center; justify-content: space-between; padding-left: 5px;">
       <div style="display: flex; align-items: center;">
        

        <input type="text" v-model="searchKeyword" placeholder="输入关键词搜索" style="margin-right: 10px; width: 200px;">
        <button @click="search">
          <i class="el-icon-search"></i>
        </button>
       </div>
       <div style="display: flex; align-items: center;">
        <button @click="fetchData" style="margin-left: 50px;">加载数据库内容</button>
        <button @click="exportToExcel" style="margin-left: 50px;">导出为Excel</button>
       </div>
      </div>
    <div class="table-container">
    <table class="custom-table">
      <thead>
        <tr>
          <th>序号</th>
          <th>组部件编号</th>
          <th>组部件名称</th>
          <th>站位</th>
          <th>工位</th>
          <th>批次</th>
          <th>开始装配时间</th>
          <th>指令交付节点</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(item, index) in currentData" :key="item.field1">
          <td>{{ index+1+(currentPage-1)*itemsPerPage }}</td>
          <td>{{ item.field1 }}</td>
          <td>{{ item.field2 }}</td>
          <td>{{ item.field3 }}</td>
          <td>{{ item.field4 }}</td>
          <td>{{ item.field5 }}</td>
          <td>{{ item.field6 }}</td>
          <td>{{ item.field7 }}</td>
        </tr>
      </tbody>
    </table>
    </div>

    <div class="pagination">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="userItemsPerPage"
        layout="total, sizes, prev, pager, next, jumper"
        :total="data.length">
      </el-pagination>
    </div>
    </div>
      </div>
</template>

<script>
import axios from 'axios';
import * as XLSX from 'xlsx';
export default {
  data() {
    return {
      currentPage: 1, // 当前页码
      userItemsPerPage: 10, // 每页显示条数
      activeTab: 'content1', // 默认选中的标签
      tableData : [],
        activeContent:'',
      items:[],//从数据库中获得的数据
      currentData:[/*当前页面的数据*/],
      data: [/* 初始数据 */],
      currentPage: 1,
      itemsPerPage: 3,
      searchKeyword: '',
    };
  },

  computed: {
       displayedData() {
      const startIndex = (this.currentPage - 1) * this.pageSize;
      const endIndex = startIndex + this.pageSize;
      return this.currentData.slice(startIndex, endIndex);
    },
filteredData() {
  let maximum;
  if (!this.searchKeyword) {
    return this.data;
  }
if(this.activeContent ==='content1'){
  maximum = 6;
}else if (this.activeContent==='content2'){
  maximum = 7;
}
  return this.data.filter(item => {
    for (let i = 1; i <= maximum; i++) {
      const field = item[`field${i}`];
      if (typeof field === 'string' && field.includes(this.searchKeyword)) {
        return true;
      } else if (typeof field === 'number' && field.toString().includes(this.searchKeyword)) {
        return true;
      }
    }
    return false;
  });
},

    totalPages() {
      return Math.ceil(this.filteredData.length / this.itemsPerPage);
    }
  },
  methods: {
    handleSizeChange(val) {
      this.userItemsPerPage = val; // 更新每页显示条数
      this.updateCurrentData(); // 调用方法更新当前数据
    },
    handleCurrentChange(val) {
      this.currentPage = val; // 更新当前页码
      this.updateCurrentData(); // 调用方法更新当前数据
    },
    handleTabClick(tab) {
      this.showContent(tab.name);
    },
    showContent(content) {
      this.activeTab = content;
    },
    exportToExcel() {
      const data = this.data;
      const adjustedData = data.map(obj => Object.values(obj));
      const worksheet = XLSX.utils.aoa_to_sheet(adjustedData);
      const workbook = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');

      const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
      const blob = new Blob([excelBuffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
      const url = URL.createObjectURL(blob);

      const link = document.createElement('a');
      link.href = url;
      link.setAttribute('download', 'exported_data.xlsx');
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    },
          showContent(content) {
      this.activeContent = content;
      this.data = []
      this.fetchData()
    },
     async fetchData() {
      try {
       this.data = []
       let response
        // 发送请求获取数据
        if(this.activeContent === 'content1'){
        response = await axios.get('http://localhost:8000/api/plan/query1');
                   // 判断是否成功获取了数据
    if (response) {
      // 将获取的数据存储在组件中
      this.items = response.data;
       // 遍历 items 中的每个对象，将数据更新到 data 中
       
      this.items.forEach(item => {
        const newDataObject = {};
        newDataObject['field1'] = item.helicopter_number;//直升机编号
        newDataObject['field2'] = item.line;//产线
        newDataObject['field3'] = item.model;//机型
        newDataObject['field4'] = item.batch;//批次
        newDataObject['field5'] = item.start_date;//开始装配时间
        newDataObject['field6'] = item.delivery_date;//指令交付节点

        this.data.push(newDataObject);
        this.currentData = this.getCurrentPageData(this.data, this.currentPage, this.itemsPerPage)
        },

      );
    } else {
      console.error('Failed to fetch data.');
      alert('Failed to fetch data.');
    }
         }else if(this.activeContent === 'content2'){
          response = await axios.get('http://localhost:8000/api/plan/query2');
                     // 判断是否成功获取了数据
    if (response) {
      // 将获取的数据存储在组件中
      this.items = response.data;
      console.log('Data fetched successfully:', this.items);
       // 遍历 items 中的每个对象，将数据更新到 data 中
       
      this.items.forEach(item => {
        const newDataObject = {};
        newDataObject['field1'] = item.module_number;//组部件编号
        newDataObject['field2'] = item.module_name;//组部件名称
        newDataObject['field3'] = item.position_zw;//站位
        newDataObject['field4'] = item.position;//工位
        newDataObject['field5'] = item.batch;//批次
        newDataObject['field6'] = item.start_date;//开始装配时间
        newDataObject['field7'] = item.delivery_date;//指令交付节点

        this.data.push(newDataObject);
        this.currentData = this.getCurrentPageData(this.data, this.currentPage, this.itemsPerPage)
        },

      );
    } else {
      console.error('Failed to fetch data.');
      alert('Failed to fetch data.');
    }
         }
 
      } catch (error) {
        console.error('Error fetching data:', error);
      }
    },

    firstPage() {
      this.currentPage = 1;
      this.currentData = this.getCurrentPageData(this.data, this.currentPage, this.itemsPerPage);
    },
    prevPage() {
      if (this.currentPage > 1) {
        this.currentPage--;
      this.currentData = this.getCurrentPageData(this.data, this.currentPage, this.itemsPerPage);
      }
    },
    nextPage() {
      if (this.currentPage < this.totalPages) {
        this.currentPage++;
      this.currentData = this.getCurrentPageData(this.data, this.currentPage, this.itemsPerPage);
      }
    },
    lastPage() {
      this.currentPage = this.totalPages;
    this.currentData = this.getCurrentPageData(this.data, this.currentPage, this.itemsPerPage);
    },
    search() {
      console.log(this.filteredData)
     this.currentData = this.getCurrentPageData(this.filteredData, this.currentPage, this.itemsPerPage)
      // 执行搜索
    },

  getCurrentPageData(data, currentPage, itemsPerPage) {
    const startIndex = (currentPage - 1) * itemsPerPage;
    const endIndex = startIndex + itemsPerPage;
    return data.slice(startIndex, endIndex);
},

  }
};
</script>

<style>
.tabs-container {
  width: 100%; /* 使容器宽度为100% */
}

.full-width-tabs .el-tabs__header {
  display: flex;
  justify-content: center; /* 居中标签页 */
  width: 100%; /* 使标签页宽度为100% */
  border-bottom: 1px solid transparent; /* 去掉底部边框 */
}

.full-width-tabs .el-tabs__header::after {
  display: flex;
  justify-content: center; /* 居中标签页 */
  width: 100%; /* 使标签页宽度为100% */
  border-bottom: 1px solid rgba(0, 0, 0, 0.1);
}

.full-width-tabs .el-tabs__item {
  flex: 1;
  text-align: center; /* 标签页文本居中 */
  font-family: '微软雅黑', sans-serif; /* 设置字体为微软雅黑 */
  font-weight: bold; /* 设置为加粗 */
  font-size: 20px; /* 设置字号为30px */
}

.full-width-tabs .el-tabs__item.is-active {
  color: #02478e !important; /* 激活状态下的标签文字颜色 */
  border-bottom-color: #02478e;
}
.table-container {
  text-align: center;
  margin: auto;
}

.custom-table {
  border-collapse: collapse;
  width: 80%;
  margin-bottom: 20px;
}

.custom-table th,
.custom-table td {
  border: 1px solid black;
  padding: 8px;
}

.pagination {
  margin-top: 20px;
}

.pagination button {
  margin-right: 5px;
}
</style>
